<?php
namespace Admin\Controller;

use Think\Controller;
class CategoryController extends CommonController
{
    private $category;

    public function __construct()
    {

        parent::__construct();
        $this->category = D("category");
    }

    public function index()
    {
/*
        $categories = $this->category->where("parent_id=0")->order("sort_order")->select();
     // dump($categories);
        foreach($categories as $key=>&$value){
            $value["children"]=$this->category->where("parent_id=$value[id]")->order("sort_order")->select();
        }
        //dump($categories,1,"",0);
        //exit;*/
        /* if(!F('tpcms_category_categories')){
             $categories=$this->category->where("parent_id=0")->relation(true)->order("sort_order")->select();
             F('tpcms_category_categories',$categories);//把$categories 存到缓存
         }
             $categories=F('tpcms_category_categories');//直接取出缓存  */
        //dump($categories,1,'',0);
        //exit;
        $categories=$this->category->where("parent_id=0")->relation(true)->order("sort_order")->select();
        $this->assign("categories", $categories);

        $this->display();
    }

    public function add()
    {
        $categories = $this->category->where("parent_id=0")->order("sort_order")->select();
        // dump($categories);
        foreach($categories as $key=>&$value){
            $value["children"]=$this->category->where("parent_id=$value[id]")->order("sort_order")->select();
        }
        //dump($categories,1,"",0);
        //exit;
        $this->assign("categories", $categories);
        $this->display();

    }

    public function do_add()
    {

        $this->category->create();
        $this->category->add();
        $this->success("增加成功", U("category/index"));

    }

    public function edit()
    {
        $id = I("get.id");
        $category = $this->category->find($id);


        $this->assign("category", $category);
        $this->display();
    }

    public function do_edit()
    {
        $id = I("get.id");
        $this->category->create();
        $this->category->where("id='$id'")->save();
        $this->success("修改成功", U("category/index"));

    }

    public function destroy()
    {
        $id = I("get.id");
        $this->category->where("id='$id'")->delete();
        $this->success("删除成功");

    }

    public function sort_order()
    {

        //dump($_POST);
       //exit;
        $sort_id = I("post.sort_id");
        $sort_order = I("post.sort_order");
        foreach ($sort_id as $key => $value) {
            $this->category->where("id=$value")->setField('sort_order', $sort_order[$key]);
        }
        $this->redirect('index');

    }
}